package com.yunduo.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yunduo.common.RetunData.CommonReturn;
import com.yunduo.common.RetunData.statuscode.impl.ResultCode;
import com.yunduo.common.RetunData.statuscode.impl.ServerCode;
import com.yunduo.common.RetunData.statuscode.impl.ServiceCode;
import com.yunduo.common.YunDuoConst.GoodTypeParam;
import com.yunduo.common.YunDuoUtils;
import com.yunduo.entity.Good;
import com.yunduo.entity.GoodType;
import com.yunduo.entity.vo.TreeData;
import com.yunduo.service.GoodService;
import com.yunduo.service.GoodTypeService;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 *  商品类型控制器
 * </p>
 *
 * @author ChengXin
 * @since 2023-07-12
 */
@RequiresRoles("user")
@RestController
@RequestMapping("/goodType")
public class GoodTypeController {

    @Resource
    private GoodTypeService goodTypeService;
    @Resource
    private GoodService goodService;

    //查询分类
    @PostMapping("/getTypes")
    public CommonReturn getTypesByIds(@RequestBody String[] ids){
        LambdaQueryWrapper<GoodType> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(GoodType::getId,ids);
        List<GoodType> typeList = goodTypeService.list(queryWrapper);
        return CommonReturn.SUCCESS(ResultCode.SUCCESS).setData("list",typeList);
    }
    //查询顶级分类
    @GetMapping("/getTypeLast")
    public CommonReturn getTypeLast(){
        LambdaQueryWrapper<GoodType> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(GoodType::getParentId,GoodTypeParam.PARENT_ID_DEFAULT);
        List<GoodType> data = goodTypeService.list(queryWrapper);
        List<TreeData> list = new ArrayList<>();
        data.forEach(item->list.add(new TreeData(item.getId(),item.getType(),null)));
        return CommonReturn.SUCCESS(ResultCode.SUCCESS).setData("list",list);
    }
    //获取分类信息
    @GetMapping("/goodType/{id}")
    public CommonReturn getGoodTypeById(@PathVariable("id")String id){
        GoodType goodType = goodTypeService.getById(id);
        if(null ==goodType){
            CommonReturn.ERROR(ResultCode.ERROR).setMessage(ServiceCode.TPYE_IS_EMPTY.getInfo());
        }
        return CommonReturn.SUCCESS(ResultCode.SUCCESS);
    }

    //添加分类
    @PostMapping("/addGoodType")
    public CommonReturn addGoodType(@RequestBody GoodType goodType){
        LambdaQueryWrapper<GoodType> queryWrapper = new LambdaQueryWrapper<GoodType>().eq(GoodType::getType, goodType.getType());
        GoodType isExist = goodTypeService.getOne(queryWrapper);
        if(isExist!=null){
            return CommonReturn.ERROR(ServiceCode.IS_EXIST);
        }
        goodTypeService.save(goodType);
        return CommonReturn.SUCCESS(ResultCode.SUCCESS).setData("id",goodType.getId());
    }

    //修改分类
    @PostMapping("/updateGoodType")
    public CommonReturn updateGoodType(@RequestBody GoodType goodType){
        goodTypeService.updateById(goodType);
        return CommonReturn.SUCCESS(ResultCode.SUCCESS);
    }

    //删除分类
    @DeleteMapping("/deleteGoodType/{id}")
    public CommonReturn deleteGoodType(@PathVariable("id") String id){
        TreeData childrenAllByTreeData = getChildrenAllByTreeData(new TreeData(id, null, null));
        boolean isDelete = goodTypeService.deleteTreeData(childrenAllByTreeData);
        if(!isDelete){
            return CommonReturn.ERROR(ResultCode.ERROR);
        }
        return CommonReturn.SUCCESS(ResultCode.SUCCESS);
    }

    //批量删除分类
    @DeleteMapping("/deleteGoodTypes")
    public CommonReturn deleteGoodType(@RequestBody String[] ids){
        List<String> list = Arrays.asList(ids);
        goodTypeService.removeByIds(list);
        list.forEach(item->goodTypeService.deleteTreeData(new TreeData(item)));
        return CommonReturn.SUCCESS(ResultCode.SUCCESS);
    }

    //获取树形数据列表
    @PostMapping("/getGoodTypes")
    public CommonReturn getGoodTypes(){
        List<TreeData> list = new ArrayList<>();
        List<GoodType> topList = goodTypeService.list(buildQueryByParentId(GoodTypeParam.PARENT_ID_DEFAULT));
        topList.forEach(item -> {
            TreeData treeData = getChildrenAllByTreeData(new TreeData(item));
            list.add(treeData);
        });
        return CommonReturn.SUCCESS(ResultCode.SUCCESS).setData("list",list);
    }

    //获取子节点的数据
    @PostMapping("/getGoodTypesById/{id}")
    public CommonReturn getGoodTypesById(@PathVariable("id") String id){
        List<TreeData> childrenById = getChildrenById(id);
        return CommonReturn.SUCCESS(ResultCode.SUCCESS).setData("list",childrenById);
    }

    //根据id获取子结点数据
    @GetMapping("/get/{id}")
    public CommonReturn getGoodTypes(@PathVariable("id")String id){
        TreeData data = getChildrenAllByTreeData(new TreeData(id, null, null));
        return CommonReturn.SUCCESS(ResultCode.SUCCESS).setData("treeData",data);

    }

    //模糊查询分类
    @PostMapping("/like")
    public CommonReturn getGoodTypeLikeName(@RequestBody String name){
        LambdaQueryWrapper<GoodType> queryWrapper = new LambdaQueryWrapper<GoodType>().likeRight(GoodType::getType, name);
        List<GoodType> list = goodTypeService.list(queryWrapper);
        return CommonReturn.SUCCESS(ResultCode.SUCCESS).setData("list",list);
    }
    //构建子类查询条件
    private LambdaQueryWrapper<GoodType> buildQueryByParentId(String prentId ){
        LambdaQueryWrapper<GoodType> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(GoodType::getParentId,prentId);
        return lambdaQueryWrapper;
    }

    //根据id获取子类
    private List<TreeData> getChildrenById(String id){
        LambdaQueryWrapper<GoodType> lambdaQueryWrapper = buildQueryByParentId(id);
        List<GoodType> list = goodTypeService.list(lambdaQueryWrapper);
        List<TreeData> treeData = new ArrayList<>();
        list.forEach(item -> treeData.add(new TreeData(item)));
        return treeData;
    }

    //递归遍历类型找到该类型的所有子集
    private TreeData getChildrenAllByTreeData(TreeData treeData){
        //拉取所有子集
        List<TreeData> children = getChildrenById(treeData.getId());
        treeData.setChildren(children);
        //遍历是否还有子集的子集
        for (int i = 0; i < children.size() ; i++){
            List<TreeData> data = getChildrenById(children.get(i).getId());
            //当前元素为空返回
            if(data == null || data.size() == 0){
                children.get(i).setChildren(null);
                continue;
            }
            children.get(i).setChildren(data);
            //不为空继续查询
            getChildrenAllByTreeData(children.get(i));
        }
        //递归
        //如果没有子集,将自己封装
        return treeData;
    }

//递归删除参考
//    //删除树形结构数据
//    private boolean deleteTreeData(TreeData treeData){
//        List<TreeData> children = treeData.getChildren();
//        for (int i = 0; i < children.size(); i++) {
//            if(children.get(i).getChildren() == null || children.get(i).getChildren().size() == 0){
//                goodTypeService.removeById(children.get(i).getId());
//                children.remove(i);
//                continue;
//            }
//            deleteTreeData(children.get(i));
//            //遍历到底层,开始递归删除
//        }
//        goodTypeService.removeById(treeData.getId());
//        return true;
//    }
}
